#include <stdio.h>
#include "wifi.h"
#include "esp_log.h"
#include "mqtt_helper.h"
#include "uart_comp.h"

#define TAG "LONGYN"

#define REMOTE_CONTROL_REQUEST_TOPIC "remote_control_request"
#define REMOTE_CONTROL_RESPONSE_TOPIC "remote_control_response"

#define WIFI_SSID "almost A"
#define WIFI_PASS "18970467709"
#define MQTT_BROKER_URI "mqtt://120.79.71.201"
#define MQTT_BROKER_PORT 1883
#define MQTT_CLIENT_ID "abc1237687688"

void uart_receive_callback(const uint8_t *data, size_t len)
{
    // 处理接收到的数据
    ESP_LOGI(TAG, "UART Received: %.*s", len, (char *)data);
    mqtt_publish_topic(REMOTE_CONTROL_RESPONSE_TOPIC, (const char *)data, 0, 0);
}

void mqtt_listener(mqtt_state_t state, void *arg)
{
    switch (state)
    {
    case MQTT_STATE_CONNECTED:
        ESP_LOGI(TAG, "MQTT connected");
        mqtt_subscribe_topic(REMOTE_CONTROL_REQUEST_TOPIC, 0);
        break;
    case MQTT_STATE_DISCONNECTED:
        ESP_LOGI(TAG, "MQTT disconnected");
        break;
    case MQTT_STATE_DATA:
        mqtt_message_t *msg = (mqtt_message_t *)arg;
        ESP_LOGI(TAG, "MQTT data received  payload: %s topic: %s", msg->payload, msg->topic);
        if (strcmp(msg->topic, REMOTE_CONTROL_REQUEST_TOPIC) == 0)
        {
            uart_send_data(msg->payload, strlen(msg->payload));
        }

        break;
    default:
        break;
    }
}

void app_main(void)
{
    uart_init(uart_receive_callback);
    wifi_init(WIFI_SSID, WIFI_PASS);
    mqtt_start(MQTT_BROKER_URI, MQTT_BROKER_PORT, MQTT_CLIENT_ID, NULL, NULL, mqtt_listener);
    ESP_LOGI(TAG, "Smart Home Started");
}